package com.tange.feature.development.toolkit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;

import com.base.BaseActivity;
import com.tange.core.backend.service.api.CoreApiUrl;
import com.tange.core.backend.service.http.CoreHttpClient;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.android.TGToast;
import com.tange.base.toolkit.ClipboardUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class HttpInterceptDetailActivity extends BaseActivity {

    public static void launch(Context context, String url, int responseCode, String request, String response, String time) {
        Intent intent = new Intent(context, HttpInterceptDetailActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("responseCode", responseCode);
        intent.putExtra("request", request);
        intent.putExtra("response", response);
        intent.putExtra("time", time);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_http_request_detail);
        hideActionBar();


        TextView url = findViewById(R.id.url);
        TextView code = findViewById(R.id.code);
        TextView request = findViewById(R.id.request);
        TextView response = findViewById(R.id.response);

        url.setText(getIntent().getStringExtra("url"));
        code.setText("状态码：" + getIntent().getIntExtra("responseCode", 0) + "      时间：" + getIntent().getStringExtra("time"));
        request.setText(getIntent().getStringExtra("request"));
        response.setText(getIntent().getStringExtra("response"));


        findViewById(R.id.repeat).setOnClickListener(v -> {
            repeat();
        });

        /**
         * 拼接命令：
                 curl -H "Content-Type: application/json; charset=UTF-8"
                 -H "Host: api-test.tange365.com"
                 -H "User-Agent: okhttp/4.10.0"
                 --data-binary "{\"appstore\":\"default\"\"}"
                 --compressed "http://api-test.tange365.com/app/v1/device/service"
         */
        findViewById(R.id.curl).setOnClickListener(v -> {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("curl -H \"Content-Type: application/json; charset=UTF-8\"");

            String host = "  -H \"Host: " + CoreApiUrl.TG_HOST.replace("https://", "").replace("http://", "").replace("/", "") + "\"";
            stringBuilder.append(host);
            stringBuilder.append("  -H \"User-Agent: okhttp/4.10.0\"");
            String params = getIntent().getStringExtra("request");
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(params);
            String dest = m.replaceAll("");
            stringBuilder.append("  --data-binary " + "\"" + dest.replace("\"", "\\\"") + "\"");
            stringBuilder.append("  --compressed " + "\"" + getIntent().getStringExtra("url") + "\"");

            ClipboardUtils.copyToClipboard(v.getContext(), stringBuilder.toString());

            TGToast.showToast("已拷贝到剪贴板");
        });
    }

    private void repeat() {

        TGThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = CoreHttpClient.getOkHttpClient();
                    Request r = new Request.Builder().url(getIntent().getStringExtra("url"))
                            .post(RequestBody.create(MediaType.get("application/json"), getIntent().getStringExtra("request"))).build();
                    Response resp = okHttpClient.newCall(r).execute();
                    ResponseBody body = resp.body();
                    if (resp.isSuccessful()) {
                        TGToast.showToast("请求成功，请返回列表顶部，然后点击查看详情");
                    } else {
                        TGToast.showToast("请求失败，请返回列表顶部，然后点击查看详情");
                    }
                } catch (Throwable ex) {
                    TGToast.showToast("请求失败: " + ex.toString());
                }
            }
        });
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void initView() {
    }
}